<?php

namespace app\admin\controller;

use app\common\model\Manager;
use app\common\model\Member;
use app\common\model\MemberPackages;
use think\captcha\Captcha;
use think\Db;

/**
 * 后台首页控制器
 */
class Index extends Home
{

    /**
     * 获取验证码
     * @return \think\Response
     */
    public function makeCaptcha()
    {
        $captcha = new Captcha();
        return $captcha->entry();
    }

    /**
     * 后台首页
     */
    public function index()
    {
        $mid = is_admin_login();
        $mname = Db('manager')->where('mid', $mid)->value('mname');
        $sql = "select sum(income) as income,sum(expend) as expend,sum(bonus1) as bonus1,sum(bonus2) as bonus2 from zx_finance ";
        $alist = Db('finance')->query($sql);


        $list = $this->financeFilter($alist);
        $list[0]['surplus'] = $list[0]['income'] - $list[0]['expend'];

        // 人数统计
        $total_num_arr = [];
        for ($i = 1; $i <= 3; $i++) {
            $map = [
                'status' => $i
            ];

            $totalNum = Db('member')->where($map)->count();
            array_push($total_num_arr, $totalNum);
        }

        // 级别统计
        $levels = \app\common\model\Levels::field('id,name')->order('id asc')->select();
        $maps['status'] = ['>=', 1];
        foreach ($levels as $val) {
            $num = Member::where($maps)->where('userrank', $val['id'])->count();
            $val->num = $num;
        }

//    记录第一次签到时间
//        $sql1 = "select min(create_time) as start_time,uid from zx_member_signin group by uid";
//        $lists = Db()->query($sql1);
//
//        foreach ($lists as $val) {
//            Db('member')->where('uid', $val['uid'])->update(['start_sign_time' => $val['start_time'], 'end_sign_time' => $val['start_time']]);
//        }

        $this->assign('total_num_arr', $total_num_arr);

        $this->assign('list', $list[0]);
        $this->assign('mname', $mname);
        $this->assign('levels', $levels);

        $this->assign('title', '首页');

        return $this->fetch();
    }

    /**
     * 拨出比计算
     * @param $list
     * @return mixed
     */
    private function financeFilter($list)
    {
        foreach ($list as &$v) {
            $v['surplus'] = sprintf("%0.2f", $v['income'] - $v['expend']);

            if ($v['income'] == 0) {
                $v['outrate'] = 100.00;
            } else {
                $v['outrate'] = round($v['expend'] / $v['income'], 4) * 100;
            }
        }
        return $list;
    }

    /**
     * 后台用户登录
     */
    public function login($username = null, $password = null)
    {
        if (request()->isPost()) {

            $verify = trim(input('post.verify'));
            if ('' === $verify) {
                $this->error('验证码不能为空');
            }
            if (!captcha_check($verify)) {
                $this->error('验证码错误');
            }

//            $code = input('code');
//            if ($code != session('phone_verify_code')) {
//                $this->error('手机验证码错误');
//            }

            $manager = Db('manager')->where('mname', $username)->find();
            if (!$manager || 1 != $manager['status']) {

                $this->error('管理员不存在或已冻结！');
            }
            /* 调用UC登录接口登录 */
            $managerObj = new Manager();
            $uid = $managerObj->login($manager, $password);
            if (0 < $uid) { //UC登录成功
                /* 登录用户 */
                $this->success('登录成功！', url('Index/index'));
            } else { //登录失败
                switch ($uid) {
                    case -101:
                        $error = '密码错误！';
                        break;
                    default:
                        $error = '未知错误！';
                        break; // 0-接口参数错误（调试阶段使用）
                }
                $this->error($error);
            }
        } else {
            $this->assign('title', '管理员登录');
            return $this->fetch();
        }
    }


    /* 退出登录 */
    public function logout(Manager $manager)
    {
        if (is_admin_login()) {
            $manager->logout();
            $this->success('退出成功！', url('login'));
        } else {
            $this->redirect('login');
        }
    }

    public function verify()
    {
        if (C('VERIFY_TYPE') == 4) {
            $zhset = C('ZH_FONT');
            $zhset = empty($zhset) ? '们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这' : $zhset;
            $config = array(
                'useZh' => true,
                'zhSet' => $zhset,
                'length' => 6,     // 验证码位数
                'useNoise' => false, // 关闭验证码杂点
                'useCurve' => false,
            );
        } else {
            if (C('VERIFY_TYPE') == 1) {
                $codeSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            } elseif (C('VERIFY_TYPE') == 2) {
                $codeSet = '0123456789';
            } else {
                $codeSet = '0123456789ABCDEFGHGKLMNPQRST';
            }
            $config = array(
                'codeSet' => $codeSet,
                'length' => 6,     // 验证码位数
                'fontttf' => '4.ttf',
                'useNoise' => false, // 关闭验证码杂点
                'useCurve' => false,

            );
        }
    }

    /**
     * 更新会员级别
     */
    public function downRank()
    {
        $bonus = new \app\common\api\controller\Bonus();
        $memberModel = Member::where('userrank', '>=', 1)->order('uid asc')->select();
        foreach ($memberModel as $val) {
            $bonus->updateRank1($val->uid);
        }

        echo 'success';
        die;
    }
}
